//
//  RYCHTTPListModel.m
//  Cashier
//
//  Created by hemingway payegis on 13-2-1.
//  Copyright (c) 2013年 payegis. All rights reserved.
//

#import "RYCHTTPListModel.h"

@interface RYCHTTPListModel ()
{
    BOOL _hasNextPage;
}
@property (nonatomic, retain) NSMutableArray* lastResponseList;
@property (nonatomic, retain) NSMutableArray* allResponseList;
@end


@implementation RYCHTTPListModel

- (void)dealloc
{
    self.lastResponseList = nil;
    self.allResponseList = nil;
    self.pagingPolicy = nil;
    [super dealloc];
}

- (NSDictionary*)pagingParams
{
    if (_pagingPolicy)
    {
        return [_pagingPolicy pagingParamsForSendRequest:self];
    }
    return nil;
}

- (void)sendRequest:(RYCHTTPRequestModelOperation)operation
{
    self.operation = operation;
    [self sendRequest];
}

- (void)reset
{
    [super reset];
    self.lastResponseList = nil;
    self.allResponseList = nil;
    _hasNextPage = NO;
    if (_pagingPolicy)
    {
        [_pagingPolicy reset:self];
    }
}

- (BOOL)handleResponseJSON:(id)aJSON
{
    id json = [self extractJSONResponse:aJSON];
    
    if (![json isKindOfClass:[NSArray class]])
    {
        return NO;
    }
    
    NSMutableArray* contentArray = [NSMutableArray array];
    for (NSDictionary* contentJSON in json)
    {
        id content = [self parseContent:contentJSON];
        if (content)
        {
            [contentArray addObject:content];
        }
    }
    
    if (nil == _lastResponseList)
    {
        self.lastResponseList = [NSMutableArray array];
    }
    [self.lastResponseList removeAllObjects];
    [self.lastResponseList addObjectsFromArray:contentArray];
    
    if (nil == _allResponseList)
    {
        self.allResponseList = [NSMutableArray array];
    }
    
    if (RYCHTTPRequestModelOperation_Normal == self.operation
        || RYCHTTPRequestModelOperation_Refresh == self.operation)
    {
        [self.allResponseList removeAllObjects];
        [self.allResponseList addObjectsFromArray:contentArray];
    }
    else if (RYCHTTPRequestModelOperation_Forward == self.operation)
    {
        [self.allResponseList addObjectsFromArray:contentArray];
    }
    else if (RYCHTTPRequestModelOperation_Backward == self.operation)
    {
        NSIndexSet* indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [contentArray count])];
        [self.allResponseList insertObjects:contentArray atIndexes:indexSet];
    }
    
    _hasNextPage = NO;
    if (_pagingPolicy)
    {
        _hasNextPage = [_pagingPolicy hasNextPage:self];
        [_pagingPolicy didModelFinished:self];
    }
    return YES;
}

- (id)extractJSONResponse:(id)aJSON
{
    return aJSON;
}

- (id)parseContent:(id)content
{
    return nil;
}
@end
